import React, { useEffect, useState } from 'react';
import styles from '../planPage/index.less';
import { Checkbox, Col, Input, Radio, Row, Select, Space, Tooltip } from 'antd';
import DealUnit from '../../components/dealUnit';
import { features, useTablePipeline } from 'ali-react-table';
import TacticPage from '../../plan/tacticPage';
import _ from 'lodash';
import { TjTable } from '@/pages/ETrade/components';
import { QuestionCircleOutlined } from '#/utils/antdIcons';
import {
  ELECTRIC_ENERGY_OPTIONS,
  ELECTRIC_PRICE_OPTIONS,
  TOOLTIP_INFO,
  unitStyle,
} from '../../constant';
import { connect } from 'umi';
import {
  buildDataKey,
  buildStationObjByData,
  buildTimeFrameArrTatic1,
  changePrice,
  disabledDate,
  getPercent,
  getThreeDecimal,
  tableStyle,
  TimeFrameArr,
} from '../../helper';
import DatePickerMultiple from '../../components/DatePickerMultiple';

const { Option } = Select;

const inputStyle = { width: 64, height: 24, fontSize: 12, padding: 3, marginLeft: 2 };

const tooltipStyle = { color: 'rgba(253, 79, 67, 1)', marginLeft: 5 };
const Tactic1 = ({
  endOrder,
  type,
  strategyData = {},
  planData,
  index,
  activeKey,
  selectRowsObj,
  dispatch,
  disabled,
}) => {
  // 当限额条件电力选择为按照最大限额申报时，表格内的电力百分比默认为100%，且不可修改
  const [checkDisabled, setCheckDisabled] = useState(false);

  useEffect(() => {
    // 当限额条件电力选择为按照最大限额申报时，表格内的电力百分比默认为100%，且不可修改
    if (strategyData.electricEnergy === 1) {
      let data = _.cloneDeep(planData);
      data[+activeKey].strategyList[index].details?.forEach((i) => {
        i.electricType = 1;
        i.electric1 = 100;
      });
      dispatch({
        type: 'interprovincialSpotDeclaration/setState',
        payload: {
          planData: data,
        },
      });
      setCheckDisabled(true);
    } else {
      setCheckDisabled(false);
    }
  }, [strategyData.electricEnergy]);

  const changeInfoData = (v, key, rowKey) => {
    let data = _.cloneDeep(planData);
    data[+activeKey].strategyList[index].details[rowKey][key] = v;
    dispatch({
      type: 'interprovincialSpotDeclaration/setState',
      payload: {
        planData: data,
      },
    });
  };

  const columns = [
    {
      code: 'timePeriod',
      name: '时间段',
      align: 'center',
      render: (_, record) => record.startOrder + '-' + record.endOrder,
    },
    {
      name: '电力',
      align: 'center',
      children: [
        {
          name: (
            <>
              <span>比例</span>
              <span style={unitStyle}>(%)</span>
            </>
          ),
          code: 'proportion',
          align: 'center',
          render: (_, record) => {
            const isChecked = record.electricType === 1;
            return (
              <Radio
                disabled={disabled || checkDisabled}
                checked={isChecked}
                onClick={() => {
                  changeInfoData(1, 'electricType', record.key);
                }}
              >
                <Input
                  type={'number'}
                  disabled={!isChecked || disabled || checkDisabled}
                  max={100}
                  min={0}
                  value={record.electric1}
                  style={inputStyle}
                  onChange={(e) => {
                    const value = getPercent(e.target.value);
                    changeInfoData(value, 'electric1', record.key);
                  }}
                />
              </Radio>
            );
          },
        },
        {
          name: (
            <>
              <span>固定值</span>
              <span style={unitStyle}>(MW)</span>
            </>
          ),
          code: 'fixedValue',
          align: 'center',
          render: (_, record) => {
            const isChecked = record.electricType === 2;
            return (
              <Radio
                disabled={disabled || checkDisabled}
                checked={isChecked}
                onClick={() => {
                  changeInfoData(2, 'electricType', record.key);
                }}
              >
                <Input
                  type={'number'}
                  disabled={!isChecked || disabled}
                  value={record.electric2}
                  style={inputStyle}
                  onChange={(e) => {
                    changeInfoData(e.target.value, 'electric2', record.key);
                  }}
                />
              </Radio>
            );
          },
        },
      ],
    },
    {
      code: 'price',
      name: (
        <>
          <div>电价</div>
          <div style={unitStyle}>(元/MW)</div>
        </>
      ),
      align: 'center',
      render: (v, record) => (
        <Input
          disabled={disabled}
          type={'number'}
          value={v}
          style={{ ...inputStyle, width: '90%' }}
          onChange={(e) => {
            const value = getThreeDecimal(e.target.value);
            changeInfoData(value, 'price', record.key, true);
          }}
        />
      ),
    },
  ];

  const onChangeOpenKeys = (v) => {
    const obj = _.cloneDeep(selectRowsObj);
    obj[index] = v;
    dispatch({
      type: 'interprovincialSpotDeclaration/setState',
      payload: {
        selectRowsObj: obj,
      },
    });
  };

  const pipeline = useTablePipeline({ components: { Checkbox } })
    .input({ dataSource: strategyData.details || [], columns })
    .primaryKey('key')
    .use(
      features.multiSelect({
        value: selectRowsObj[index] || [],
        onChange: onChangeOpenKeys,
      }),
    );

  const disablePipeline = useTablePipeline({ components: {} })
    .input({ dataSource: strategyData.details || [], columns })
    .primaryKey('key');

  const changePlanData = (data) => {
    dispatch({
      type: 'interprovincialSpotDeclaration/setState',
      payload: {
        planData: data,
      },
    });
  };

  const changeMarkDate = (v) => {
    const markDate = v.toString();
    let data = _.cloneDeep(planData);
    data[+activeKey].strategyList[index].markDate = markDate;
    const stationObj = buildStationObjByData(data);
    dispatch({
      type: 'interprovincialSpotDeclaration/setState',
      payload: {
        planData: data,
        stationObj,
      },
    });
  };

  const changeElectricEnergy = (v) => {
    let data = _.cloneDeep(planData);
    data[+activeKey].strategyList[index].electricEnergy = v;
    changePlanData(data);
  };

  const changeElectricPriceType = (v) => {
    let data = _.cloneDeep(planData);
    data[+activeKey].strategyList[index].electricPriceType = v;
    changePlanData(data);
  };

  const changeElectricPrice = (e) => {
    const value = getThreeDecimal(e.target.value);
    let data = _.cloneDeep(planData);
    data[+activeKey].strategyList[index].electricPrice = value;
    data[+activeKey].strategyList[index].details = changePrice(strategyData.details, value);
    changePlanData(data);
  };

  const changeTimeFrame = (v) => {
    const details = strategyData?.details || [];
    let arr = [];
    let timeFrame = buildTimeFrameArrTatic1(v, strategyData);
    timeFrame.forEach((i) => {
      if (details.some((a) => a.timePeriod === i.timePeriod)) {
        const value = details.filter((f) => f.timePeriod === i.timePeriod)?.[0];
        arr.push(value);
      } else {
        arr.push(i);
      }
    });
    arr = buildDataKey(arr);
    let data = _.cloneDeep(planData);
    data[+activeKey].strategyList[index]['hourOrderList'] = v;
    data[+activeKey].strategyList[index].details = arr;
    changePlanData(data);
  };

  return (
    <TacticPage title={strategyData.strategyName} index={index} disabled={disabled}>
      {type !== 'intraday' ? (
        <div className={styles.tactic_line_margin}>
          <div className={styles.tactic_line_title_box}>
            <div className={styles.tactic_line_title}>标的日</div>
            <div className={styles.tactic_line_title}>*可多选</div>
          </div>
          <DatePickerMultiple
            disabled={disabled}
            disabledDate={(current) => disabledDate(current, endOrder)}
            value={strategyData.markDate ? strategyData.markDate.split(',') : []}
            onChange={changeMarkDate}
          />
        </div>
      ) : (
        <div className={styles.tactic_line_margin}>
          <div className={styles.tactic_line_title}>时段</div>
          <div style={{ marginBottom: 8 }}>
            <Checkbox
              indeterminate={
                (strategyData?.hourOrderList?.length || 0) > 0 &&
                (strategyData?.hourOrderList?.length || 0) < TimeFrameArr.length
              }
              checked={(strategyData?.hourOrderList?.length || 0) === TimeFrameArr.length}
              disabled={disabled}
              onChange={(e) => {
                const checked = e.target.checked;
                const allValues = TimeFrameArr.map((i) => i.value);
                changeTimeFrame(checked ? allValues : []);
              }}
            >
              全选
            </Checkbox>
          </div>
          <Checkbox.Group
            className={styles.tactic_line_checkbox}
            onChange={changeTimeFrame}
            value={strategyData?.hourOrderList || []}
          >
            <Row>
              {TimeFrameArr.map((i) => (
                <Col span={4} key={i.value}>
                  <Checkbox disabled={disabled} value={i.value} key={i.value}>
                    {i.label}
                  </Checkbox>
                </Col>
              ))}
            </Row>
          </Checkbox.Group>
        </div>
      )}
      <div className={styles.tactic_line_margin}>
        <div className={styles.tactic_line_title}>交易单元</div>
        <DealUnit disabled={disabled} index={index} strategyData={strategyData} />
      </div>
      <div className={styles.table}>
        <div className={styles.tactic_line_margin}>
          <div className={styles.tactic_line_title}>
            限额条件
            <Tooltip title={TOOLTIP_INFO}>
              <QuestionCircleOutlined style={tooltipStyle} />
            </Tooltip>
          </div>
          <Space direction="vertical">
            <div className={styles.tactic_line_radio}>
              <div className={styles.tactic_line_radio_label}>电力</div>
              <Select
                disabled={disabled}
                style={{ width: '100%' }}
                placeholder={'请选择'}
                onChange={changeElectricEnergy}
                value={strategyData.electricEnergy}
              >
                {ELECTRIC_ENERGY_OPTIONS.map((i) => (
                  <Option key={i.value} value={i.value}>
                    {i.label}
                  </Option>
                ))}
              </Select>
            </div>
            <div className={styles.tactic_line_radio}>
              <div className={styles.tactic_line_radio_label}>电价</div>
              <Select
                disabled={disabled}
                style={{ width: '78%', marginRight: '2%' }}
                placeholder={'请选择'}
                value={strategyData.electricPriceType}
                onChange={changeElectricPriceType}
              >
                {ELECTRIC_PRICE_OPTIONS.map((i) => (
                  <Option key={i.value} value={i.value}>
                    {i.label}
                  </Option>
                ))}
              </Select>
              <Input
                style={{ width: '20%' }}
                disabled={disabled || strategyData.electricPriceType !== 3}
                value={strategyData.electricPrice}
                type={'number'}
                onChange={changeElectricPrice}
              />
            </div>
          </Space>
        </div>
        <div className={styles.table_box}>
          <TjTable
            style={tableStyle}
            useOuterBorder={true}
            stickyScrollHeight={10}
            useVirtual={{ horizontal: true, vertical: true, header: false }}
            defaultColumnWidth={100}
            {...(disabled ? { ...disablePipeline.getProps() } : { ...pipeline.getProps() })}
          />
        </div>
      </div>
    </TacticPage>
  );
};

export default connect(({ global, interprovincialSpotDeclaration }) => ({
  planData: interprovincialSpotDeclaration.planData,
  activeKey: interprovincialSpotDeclaration.activeKey,
  date: interprovincialSpotDeclaration.date,
  selectRowsObj: interprovincialSpotDeclaration.selectRowsObj,
  type: interprovincialSpotDeclaration.type,
  endOrder: interprovincialSpotDeclaration.endOrder,
}))(Tactic1);
